package edu.uoc.tdp.pac4.stock;

import edu.uoc.tdp.pac4.beans.PeticionRecurso;
import edu.uoc.tdp.pac4.beans.PeticionRecursoDetalle;
import edu.uoc.tdp.pac4.remote.GestorEstoc;
import edu.uoc.tdp.pac4.client.PnlMain;
import edu.uoc.tdp.pac4.util.LanguageUtils;
import java.rmi.RemoteException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 * Implementa el formulario de atención de peticiones.
 * 
 * @author eSupport Netbeans
 */
public class FrmResourcesRequestsServe extends javax.swing.JDialog 
{
   private GestorEstoc rmiManager;
   private LanguageUtils language;
   private ArrayList<PeticionRecursoDetalle> pets;

   /**
    * Creates new form FrmResourcesRequestsServe
    */
   public FrmResourcesRequestsServe(PnlMain parent, boolean modal, GestorEstoc manager, LanguageUtils language) 
   {
      super(parent, modal);
      // Obtiene los parámetros que provienen del formulario principal
      this.rmiManager = manager;
      this.language = language;
      
      // Inicializa los componentes del formulario
      initComponents();
      
      // Establece literales de texto
      this.setTitle(language.getProperty("form.resourceRequestServe.title"));
      cmdClose.setText(language.getProperty("form.common.close"));
      lblServe.setText(language.getProperty("form.resourceRequestServe.lblServe"));
      lblBloqued.setText(language.getProperty("form.resourceRequestServe.lblBloqued"));
      cmdServeRequest.setText(language.getProperty("form.resourceRequestServe.cmdServeRequest"));
      
      // Rellena las tablas
      refreshTables();
   }

   /**
    * This method is called from within the constructor to initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is always
    * regenerated by the Form Editor.
    */
   @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        cmdClose = new javax.swing.JButton();
        tabRequests = new javax.swing.JTabbedPane();
        tabPending = new javax.swing.JPanel();
        lblServe = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        grdToServe = new javax.swing.JTable();
        cmdServeRequest = new javax.swing.JButton();
        tabBloqued = new javax.swing.JPanel();
        lblBloqued = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        grdBloqued = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Servir peticiones de recursos");
        setModal(true);
        setResizable(false);

        cmdClose.setText("Cerrar");
        cmdClose.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdCloseActionPerformed(evt);
            }
        });

        lblServe.setText("Peticiones pendientes");

        grdToServe.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(grdToServe);

        cmdServeRequest.setText("Servir petición");
        cmdServeRequest.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdServeRequestActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout tabPendingLayout = new javax.swing.GroupLayout(tabPending);
        tabPending.setLayout(tabPendingLayout);
        tabPendingLayout.setHorizontalGroup(
            tabPendingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(tabPendingLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(tabPendingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(tabPendingLayout.createSequentialGroup()
                        .addComponent(lblServe)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 512, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, tabPendingLayout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(cmdServeRequest, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        tabPendingLayout.setVerticalGroup(
            tabPendingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(tabPendingLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lblServe)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 229, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cmdServeRequest)
                .addContainerGap())
        );

        tabRequests.addTab("Pendientes", tabPending);

        lblBloqued.setText("Peticiones bloqueadas por falta de stock");

        grdBloqued.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane2.setViewportView(grdBloqued);

        javax.swing.GroupLayout tabBloquedLayout = new javax.swing.GroupLayout(tabBloqued);
        tabBloqued.setLayout(tabBloquedLayout);
        tabBloquedLayout.setHorizontalGroup(
            tabBloquedLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(tabBloquedLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(tabBloquedLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 512, Short.MAX_VALUE)
                    .addGroup(tabBloquedLayout.createSequentialGroup()
                        .addComponent(lblBloqued)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        tabBloquedLayout.setVerticalGroup(
            tabBloquedLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(tabBloquedLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lblBloqued)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 264, Short.MAX_VALUE)
                .addContainerGap())
        );

        tabRequests.addTab("Bloqueadas", tabBloqued);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(cmdClose))
                    .addComponent(tabRequests, javax.swing.GroupLayout.Alignment.TRAILING))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(12, 12, 12)
                .addComponent(tabRequests)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cmdClose)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

   private void cmdCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdCloseActionPerformed
      
      // Cierra el formulario
      this.dispose();
      
   }//GEN-LAST:event_cmdCloseActionPerformed

   private void cmdServeRequestActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdServeRequestActionPerformed

      // Comprobación de datos previa
      if (grdToServe.getSelectedRow() < 0)
      {
         JOptionPane.showMessageDialog(null, 
                                       language.getProperty("form.resourceRequestServe.noRequestSelected"), 
                                       language.getProperty("app.title"), 
                                       JOptionPane.WARNING_MESSAGE);
         return;
      }
      if (grdToServe.getSelectedRow() > 0)
      {
         JOptionPane.showMessageDialog(null, 
                                       language.getProperty("form.resourceRequestServe.noFirstRowSelected"), 
                                       language.getProperty("app.title"), 
                                       JOptionPane.WARNING_MESSAGE);
         return;
      }
      
      try 
      {
         // this.setCursor(new Cursor(Cursor.WAIT_CURSOR));
         
         // Obtiene la petición
         PeticionRecursoDetalle peticion = pets.get(grdToServe.getSelectedRow());
         peticion.setFechaAceptacion(new Date());
         
         // Marca la petición como servida
         rmiManager.aceptarPeticionRecursos((PeticionRecurso)peticion);
         
         // Refresca las tablas
         refreshTables();
         
         // this.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
         
         // Muestra un mensaje de confirmación al usuario
         String msg = language.getProperty("form.resourceRequestServe.successMsg1") + "\n" + 
                      language.getProperty("form.resourceRequestServe.successMsg2") + ": " + peticion.getNomAula() + "\n" + 
                      language.getProperty("form.resourceRequestServe.successMsg3") + ": " + peticion.getNombreRecurso() + "\n" + 
                      language.getProperty("form.resourceRequestServe.successMsg4") + ": " + peticion.getCantidad() + " unidad(es)\n" + 
                      language.getProperty("form.resourceRequestServe.successMsg5") + ": " + (peticion.getStockReal() - peticion.getCantidad()) + " unidad(es)";
         JOptionPane.showMessageDialog(null, msg, language.getProperty("app.title"), JOptionPane.INFORMATION_MESSAGE);
      } 
      catch (SQLException ex)
      {
         // this.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
         JOptionPane.showMessageDialog(null, 
                                       language.getProperty("err.sql") + "\n" + language.getProperty("err.detail") + ":\n\n" + ex.getMessage(), 
                                       language.getProperty("app.title"), 
                                       JOptionPane.ERROR_MESSAGE);
         
         // Registra el error en un archivo de LOG
         // Logger.getLogger(FrmResourcesRequest.class.getName()).log(Level.SEVERE, null, ex);
      }
      catch (RemoteException ex)
      {
         // this.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
         JOptionPane.showMessageDialog(null, 
                                       language.getProperty("err.rmi") + "\n" + language.getProperty("err.detail") + ":\n\n" + ex.getMessage(), 
                                       language.getProperty("app.title"), 
                                       JOptionPane.ERROR_MESSAGE);
         
         // Registra el error en un archivo de LOG
         // Logger.getLogger(FrmResourcesRequest.class.getName()).log(Level.SEVERE, null, ex);
      }
      catch (Exception ex) 
      {
         // this.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
         JOptionPane.showMessageDialog(null, 
                                       language.getProperty("err.generic") + "\n" + language.getProperty("err.detail") + ":\n\n" + ex.getMessage(), 
                                       language.getProperty("app.title"), 
                                       JOptionPane.ERROR_MESSAGE);
         
         // Registra el error en un archivo de LOG
         // Logger.getLogger(FrmResourcesRequest.class.getName()).log(Level.SEVERE, null, ex);
      }
      
   }//GEN-LAST:event_cmdServeRequestActionPerformed
   
   private void refreshTables()
   {
      SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
      
      // Rellena la tabla
      ArrayList<String> header = new ArrayList<String>();   // cabecera
      header.add(language.getProperty("form.resourceRequestServe.grid.date"));
      header.add(language.getProperty("form.resourceRequestServe.grid.class"));
      header.add(language.getProperty("form.resourceRequestServe.grid.resource"));
      header.add(language.getProperty("form.resourceRequestServe.grid.numItems"));
      
      String[][] dataToServe;
      String[][] dataBloqued;
      List<PeticionRecursoDetalle> peticiones;
      ArrayList<String> row;

      try 
      {
         pets = new ArrayList<PeticionRecursoDetalle>();
         peticiones = rmiManager.getPeticionesRecursos();
         dataToServe = new String[peticiones.size()][4];
         dataBloqued = new String[peticiones.size()][4];
         int i = 0, j = 0;
         for (PeticionRecursoDetalle peticion : peticiones)
         {
            if (peticion.getCantidad() <= peticion.getStockReal())
            {
               dataToServe[i][0] = df.format(peticion.getFechaAltaPeticion());
               dataToServe[i][1] = peticion.getNomAula();
               dataToServe[i][2] = peticion.getNombreRecurso();
               dataToServe[i][3] = "" + peticion.getCantidad();
               i++;
               
               // Guarda las instancias para poder recuperar los datos posteriormente
               pets.add(peticion);
            }
            else
            {
               dataBloqued[j][0] = df.format(peticion.getFechaAltaPeticion());
               dataBloqued[j][1] = peticion.getNomAula();
               dataBloqued[j][2] = peticion.getNombreRecurso();
               dataBloqued[j][3] = "" + peticion.getCantidad();
               j++;
            }
         }
         
         grdToServe.setModel(new DefaultTableModel(dataToServe, header.toArray()));
         grdBloqued.setModel(new DefaultTableModel(dataBloqued, header.toArray()));
      } 
      catch (SQLException ex)
      {
         JOptionPane.showMessageDialog(null, 
                                       language.getProperty("err.sql") + "\n" + language.getProperty("err.detail") + ":\n\n" + ex.getMessage(), 
                                       language.getProperty("app.title"), 
                                       JOptionPane.ERROR_MESSAGE);
         
         // Registra el error en un archivo de LOG
         // Logger.getLogger(FrmResourcesRequest.class.getName()).log(Level.SEVERE, null, ex);
      }
      catch (RemoteException ex)
      {
         JOptionPane.showMessageDialog(null, 
                                       language.getProperty("err.rmi") + "\n" + language.getProperty("err.detail") + ":\n\n" + ex.getMessage(), 
                                       language.getProperty("app.title"), 
                                       JOptionPane.ERROR_MESSAGE);
         
         // Registra el error en un archivo de LOG
         // Logger.getLogger(FrmResourcesRequest.class.getName()).log(Level.SEVERE, null, ex);
      }
      catch (Exception ex) 
      {
         JOptionPane.showMessageDialog(null, 
                                       language.getProperty("err.generic") + "\n" + language.getProperty("err.detail") + ":\n\n" + ex.getMessage(), 
                                       language.getProperty("app.title"), 
                                       JOptionPane.ERROR_MESSAGE);
         
         // Registra el error en un archivo de LOG
         // Logger.getLogger(FrmResourcesRequest.class.getName()).log(Level.SEVERE, null, ex);
      }
   }
   
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cmdClose;
    private javax.swing.JButton cmdServeRequest;
    private javax.swing.JTable grdBloqued;
    private javax.swing.JTable grdToServe;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JLabel lblBloqued;
    private javax.swing.JLabel lblServe;
    private javax.swing.JPanel tabBloqued;
    private javax.swing.JPanel tabPending;
    private javax.swing.JTabbedPane tabRequests;
    // End of variables declaration//GEN-END:variables
}
